package com.wuliming.gulimall.ware.service.impl;

import com.wuliming.constant.WareConstant;
import com.wuliming.gulimall.ware.entity.PurchaseDetailEntity;
import com.wuliming.gulimall.ware.service.PurchaseDetailService;
import com.wuliming.gulimall.ware.service.WareSkuService;
import com.wuliming.gulimall.ware.vo.PurchaseItemVo;
import com.wuliming.gulimall.ware.vo.req.PurchaseReqVo;
import com.wuliming.gulimall.ware.vo.req.WareMergeReqVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wuliming.common.utils.PageUtils;
import com.wuliming.common.utils.Query;

import com.wuliming.gulimall.ware.dao.PurchaseDao;
import com.wuliming.gulimall.ware.entity.PurchaseEntity;
import com.wuliming.gulimall.ware.service.PurchaseService;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils unreceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
                        .eq("status", WareConstant.PurchaseStatusEnum.CREATED.getCode())
                        .or().eq("status", WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
        );
        return new PageUtils(page);
    }

    @Override
    public void merge(WareMergeReqVo wareMergeReqVo) {
        Long purchaseId = wareMergeReqVo.getPurchaseId();
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //TODO 确认采购单状态为新建或已分配才可以合并

        List<Long> items = wareMergeReqVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(id -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(id);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailEntities);
    }

    @Override
    public void received(List<Long> ids) {
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            PurchaseEntity byId = getById(id);
            return byId;
        }).filter(w -> {
            if (w.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                    w.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(w -> {
            w.setUpdateTime(new Date());
            w.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            return w;
        }).collect(Collectors.toList());
        updateBatchById(collect);

        collect.stream().forEach(w -> {
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.ListDetailByPurchaseId(w.getId());
            List<PurchaseDetailEntity> detailEntities = purchaseDetailEntities.stream().map(item -> {
                item.setStatus((WareConstant.PurchaseDetailStatusEnum.RECEIVE.getCode()));
                return item;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(detailEntities);
        });

    }

    @Override
    public void done(PurchaseReqVo purchaseReqVo) {
        Long purchaseId = purchaseReqVo.getId();
        //更新采购需求
        AtomicBoolean flag = new AtomicBoolean(true);
        List<PurchaseItemVo> purchaseDetails = purchaseReqVo.getItems();
        List<PurchaseDetailEntity> purchaseDetailEntities = new ArrayList<>();
        purchaseDetails.forEach(item ->{
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            PurchaseDetailEntity detailEntity = purchaseDetailService.getBySkuId(item.getItemId());
            purchaseDetailEntity.setId(detailEntity.getId());
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag.set(false);
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
            }else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                wareSkuService.addStock(detailEntity.getWareId(),detailEntity.getSkuId(),detailEntity.getSkuNum());
            }
            purchaseDetailEntities.add(purchaseDetailEntity);
        });
        purchaseDetailService.updateBatchById(purchaseDetailEntities);
        //更新订单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setId(purchaseId);
        if (flag.get()) {
            purchaseEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
        }else {
            purchaseEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
        }
        updateById(purchaseEntity);
    }

}